package com.example.cachecontroldemo.interceptor.impl;

import com.example.cachecontroldemo.interceptor.AbstractCacheControlValidator;
import com.example.cachecontroldemo.pojo.UserDO;
import com.example.cachecontroldemo.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;

/**
 * Component 内的 /user/{userId}，表示该类负责处理缓存验证的接口地址，多个接口用逗号分隔
 * 为防止框架将注解内容识别为Controller，使用[]代替{},在拦截器中会做还原
 */
@Component("/user/[userId]")
@RequiredArgsConstructor
public class UserDetailCacheControlValidatorImpl extends AbstractCacheControlValidator {
    private final IUserService userService;

    @Override
    public Long getLastModified(HttpServletRequest request) {
        String userId = getPathVarId(request);
        UserDO userDO = userService.getById(userId);
        LocalDateTime time = Objects.nonNull(userDO.getUpdateTime()) ? userDO.getUpdateTime() : userDO.getCreateTime();
        return time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }
}
